package org.lwxyz.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @description ssh远程操作工具类
 * @author yuwei
 * @version 1.0-SNAPSHOT
 * @date 2018-1-23 10:20:24
 */
public final class SSHUtil {
    /**
     * 服务器地址
     */
    private static String host;

    /**
     * 服务器ssh端口
     */
    private static int port;

    /**
     * ssh用户名
     */
    private static String username;

    /**
     * ssh用户密码
     */
    private static String password;

    public static void ssh(String host, int port, String username, String password){
        SSHUtil.host = host;
        SSHUtil.port = port;
        SSHUtil.username = username;
        SSHUtil.password = password;
    }

    /**
     * 获取ssh连接
     * @return
     * @throws IOException
     */
    public static Connection sshConnection() throws IOException {
        Connection connection = new Connection(host, port);
        connection.connect();//连接
        connection.authenticateWithPassword(username, password);//认证
        return connection;
    }

    /**
     * 执行命令
     * @param shell
     * @return
     * @throws IOException
     */
    public static List<String> sshResult(String shell) throws IOException{
        // 结果集
        List<String> result = Lists.newArrayList();
        // 获取ssh连接
        Connection connection = sshConnection();
        // 打开session，使用session执行命令
        Session session = connection.openSession();
        // 执行命令
        session.execCommand(shell);
        //获得标准输出流
        InputStream is = new StreamGobbler(session.getStdout());
        BufferedReader brs = new BufferedReader(new InputStreamReader(is));
        // 循环获取结果集
        for (String line = brs.readLine(); line != null; line = brs.readLine()) {
            result.add(line);
        }
        session.close();
        return result;
    }
}
